

package com.coding4play.mqtt.broker.protocol;

import com.coding4play.mqtt.common.entity.message.DupPubRelMessage;
import com.coding4play.mqtt.common.repository.IDupPubRelMessageRepository;
import com.coding4play.mqtt.common.repository.IDupPublishMessageRepository;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import io.netty.util.AttributeKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * PUBREC连接处理
 */
@Slf4j
@AllArgsConstructor
public class PubRec {

    private IDupPublishMessageRepository dupPublishMessageRepository;
    private IDupPubRelMessageRepository dupPubRelMessageRepository;

    public void processPubRec(Channel channel, MqttMessageIdVariableHeader variableHeader) {
        MqttMessage pubRelMessage = MqttMessageFactory.newMessage(
                new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_MOST_ONCE, false, 0),
                MqttMessageIdVariableHeader.from(variableHeader.messageId()), null);
        log.debug("PUBREC - clientId: {}, messageId: {}", channel.attr(AttributeKey.valueOf("clientId")).get(), variableHeader.messageId());
        dupPublishMessageRepository.delete((String) channel.attr(AttributeKey.valueOf("clientId")).get(), variableHeader.messageId());
        DupPubRelMessage dupPubRelMessage = DupPubRelMessage.builder()
                .clientId((String) channel.attr(AttributeKey.valueOf("clientId")).get())
                .messageId(variableHeader.messageId())
                .build();
        dupPubRelMessageRepository.put((String) channel.attr(AttributeKey.valueOf("clientId")).get(), dupPubRelMessage);
        channel.writeAndFlush(pubRelMessage);
    }

}
